package com.cqie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqie.dto.PrescriptionInfo.AddPrescriptionInfoDto;
import com.cqie.dto.PrescriptionInfo.PrescriptionInfoDto;
import com.cqie.entity.PrescriptionInfo;
import com.cqie.exception.SpecialException;
import com.cqie.mapper.PrescriptionInfoMapper;
import com.cqie.service.ICaseInfoService;
import com.cqie.service.IPrescriptionInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;

/**
 * <p>
 * 处方信息 服务实现类
 * </p>
 *
 * @author 不吃海鲜
 * @since 2024-12-26
 */
@Service
public class PrescriptionInfoServiceImpl extends ServiceImpl<PrescriptionInfoMapper, PrescriptionInfo> implements IPrescriptionInfoService {

    @Resource
    private PrescriptionInfoMapper prescriptionInfoMapper;

    private final ICaseInfoService caseInfoService;

    public PrescriptionInfoServiceImpl(ICaseInfoService caseInfoService) {
        this.caseInfoService = caseInfoService;
    }

    /**
     * 新增处方信息
     * @param addPrescriptionInfoDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addPrescriptionInfo(AddPrescriptionInfoDto addPrescriptionInfoDto) throws SpecialException {

        if (ObjectUtils.isEmpty(addPrescriptionInfoDto.getCaseCode())){
            throw new SpecialException("病历号不能为空");
        }

        if (ObjectUtils.isEmpty(addPrescriptionInfoDto.getDoctorId())){
            throw new SpecialException("医生id不能为空");
        }

        if (ObjectUtils.isEmpty(addPrescriptionInfoDto.getPatientId())){
            throw new SpecialException("病人id不能为空");
        }

        // 生成处方编号
        addPrescriptionInfoDto.setPrescriptionCode(generatePrescriptionCode());
        addPrescriptionInfoDto.setIsPay("0");

        // 新增开药记录
        var result = prescriptionInfoMapper.addPrescriptionInfo(addPrescriptionInfoDto);

        if (!result){
            throw new SpecialException("新增处方信息失败");
        }

        return caseInfoService.updateIsPrescribe(addPrescriptionInfoDto.getCaseCode());
    }

    /**
     * 查看处方列表
     * @param likeQuery
     * @param isPay
     * @param pageSize
     * @param pageIndex
     * @return
     */
    @Override
    public List<PrescriptionInfo> getPrescriptionInfoList(String likeQuery, String isPay, Integer pageSize,
                                                             Integer pageIndex) {
        Page<PrescriptionInfo> page = new Page<>(pageIndex, pageSize);

        // 条件
        LambdaQueryWrapper<PrescriptionInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PrescriptionInfo::getRmSign , "0");

        if (ObjectUtils.isNotEmpty(isPay)){
            queryWrapper.eq(PrescriptionInfo::getIsPay , isPay);
        }

        if (ObjectUtils.isNotEmpty(likeQuery)){
            queryWrapper
                    .like(PrescriptionInfo::getPrescriptionCode, likeQuery)
                    .or()
                    .like(PrescriptionInfo::getCaseCode, likeQuery)
                    .or()
                    .like(PrescriptionInfo::getPatientName, likeQuery);
        }


        IPage<PrescriptionInfo> result = prescriptionInfoMapper.selectPage(page, queryWrapper);
        return result.getRecords();
    }

    /**
     * 根据病例编码查看处方信息
     * @param caseCode
     * @return
     */
    @Override
    public PrescriptionInfoDto getPrescriptionInfoByCaseCode(String caseCode) {
        return prescriptionInfoMapper.getPrescriptionInfoByCaseCode(caseCode);
    }


    /**
     * 根据处方编码删除处方信息
     * @param prescriptionCode
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delPrescriptionInfo(String prescriptionCode) throws SpecialException {
        // 先查询当前状态
        var prescriptionInfo = prescriptionInfoMapper.getPrescriptionCodeByPrescriptionCode(prescriptionCode);

        if (ObjectUtils.equals(prescriptionInfo.getIsPay() , "1")){
            throw new SpecialException("已支付的处方不能删除");
        }

        // 将开药标志转换成未开药
        var result = caseInfoService.removeIsPrescribe(prescriptionInfo.getCaseCode());

        if (!result){
            throw new SpecialException("删除处方信息失败");
        }

        return prescriptionInfoMapper.delPrescriptionInfo(prescriptionCode);
    }


    /**
     * 生成处方编号
     *
     * @return
     */
    private String generatePrescriptionCode() {
        String prescriptionCode = "CF";


        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            // 随机生成0到9之间的整数，并追加到StringBuilder对象中
            sb.append(random.nextInt(10));
        }

        prescriptionCode += sb.toString();

        // 数据库查询是否存在相同的
        var num = prescriptionInfoMapper.getPrescriptionCode(prescriptionCode);
        if (num > 0) {
            return generatePrescriptionCode();
        }

        return prescriptionCode;
    }
}
